<?php
session_start();

define('USER', 'gabriel');
define('PASSWORD', 'gibsaon190988');

function login() {
    if ($_POST[user] == USER && $_POST[password] == PASSWORD) {
        $database;
        $homePage;
        $portfolioPage;
        $aboutPage;
        $contactPage;

        $database = new SimpleXMLElement('xml/database.xml', null, true);
        foreach ($database->famousQuotes->quote as $quote) {
            $strQuote = $quote->author . "§" . $quote->text;

            $homePage[] = $strQuote;
        }

        foreach ($database->portfolio->item as $item) {
            $strItem = "";
            foreach ($item as $data) {
                $strItem .= $data . '§';
            }
            $strItem = 'img/portfolio/' . $strItem;
            $strItem = rtrim($strItem, '§');
            $portfolioPage[] = $strItem;
        }

        foreach ($database->about->photo as $photo) {
            
        }
        foreach ($database->about->desc as $desc) {
            
        }
        foreach ($database->about->skills->skill as $key => $skill) {
            $skills[] = $skill->name . '§' . $skill->level;
        }

        $aboutPage['skills'] = $skills;
        $aboutPage['photo'] = '' . $photo;
        $aboutPage['desc'] = '' . $desc;

        $_SESSION['db_home'] = $homePage;
        $_SESSION['db_portfolio'] = $portfolioPage;
        $_SESSION['db_about'] = $aboutPage;
        $_SESSION['user'] = $_POST[user];
        $_SESSION['login'] = 1;

        Header('Location: ' . $_SERVER['PHP_SELF']);
    } else {
        $_SESSION['login'] = 0;
    }
}

function save() {
    if (isset($_SESSION['user']) && $_SESSION['user'] == USER) {
        $database = new SimpleXMLElement('xml/database.xml', null, true);
        unset($database->famousQuotes);
        unset($database->portfolio);
        unset($database->about);
        $famousQuotes = $database->addChild('famousQuotes');
        $XmlPortfolio = $database->addChild('portfolio');
        $XmlAboutMe = $database->addChild('about');

        foreach ($_POST['quote'] as $value) {
            $arrQuote = explode('§', $value);

            $xmlQuote = $famousQuotes->addChild('quote');
            $xmlQuote->addChild('author', $arrQuote[0]);
            $xmlQuote->addChild('text', $arrQuote[1]);
            $home[] = $value;
        }

        foreach ($_POST['portfolio'] as $item) {
            $arrItem = explode('§', $item);
            if (substr($arrItem[0], 0, 4) == 'tmp/') {
                $dest = 'img/portfolio/' . substr($arrItem[0], 4);
                if (copy($arrItem[0], $dest)) {
                    $arrItem[0] = $dest;
                } else {
                    echo '<script>alert("Não foi possível mover a imagem da pasta temporária para a pasta definitiva. Algumas informações podem não ter sido salvas.");</script>';
                    return;
                }
            }
            $thumbAddress = substr($arrItem[0], 14);
            $arrItem[3] = "TECNOLOGIAS: " . $arrItem[3];

            $xmlItem = $XmlPortfolio->addChild('item');
            $xmlItem->addChild('thumb', $thumbAddress);
            $xmlItem->addChild('name', $arrItem[1]);
            $xmlItem->addChild('desc', $arrItem[2]);
            $xmlItem->addChild('tech', $arrItem[3]);
            $xmlItem->addChild('link', $arrItem[4]);
            $xmlItem->addChild('status', $arrItem[5]);

            $strItem = implode("§", $arrItem);
            $portfolio[] = $strItem;
        }

        $myPhoto = $_POST['aboutMe_photo'];
        if (substr($myPhoto, 0, 4) == 'tmp/') {
            $dest = 'img/' . substr($myPhoto, 4);
            if (copy($myPhoto, $dest)) {
                $myPhoto = $dest;
            } else {
                echo '<script>alert("Não foi possível mover a imagem da pasta temporária para a pasta definitiva. Algumas informações podem não ter sido salvas.");</script>';
                return;
            }
        }
        $XmlAboutMe->addChild('photo', $myPhoto);
        $XmlAboutMe->addChild('desc', $_POST['aboutMe_desc']);
        $xmlSkills = $XmlAboutMe->addChild('skills');
        foreach ($_POST['aboutMe_skill'] as $skill) {
            $arrSkill = explode('§', $skill);

            $xmlSkill = $xmlSkills->addChild('skill');
            $xmlSkill->addChild('name', $arrSkill[0]);
            $xmlSkill->addChild('level', $arrSkill[1]);

            $aboutMe['skills'][] = $skill;
        }
        $aboutMe['photo'] = $myPhoto;
        $aboutMe['desc'] = $_POST['aboutMe_desc'];

        $_SESSION['db_home'] = $home;
        $_SESSION['db_portfolio'] = $portfolio;
        $_SESSION['db_about'] = $aboutMe;

        if ($database->asXML('xml/database.xml')) {
            eraseTmp();
            Header('Location: ' . $_SERVER['PHP_SELF'] . '?dataSaved=true');
        } else {
            echo '<script>alert("ERRO: Ocorreu um problema ao tentar escrever no banco de dados. As informações não foram salvas.");</script>';
        }
    } else {
        header('Location: ' . $_SERVER['PHP_SELF']);
    }
}

function uploadImage() {
    if (isset($_SESSION['user']) && $_SESSION['user'] == USER) {
        if ($_FILES['theImage']['error'] > 0) {
            echo '<script>alert("ERRO: Ocorreu um problema ao tentar fazer upload do arquivo. \n Código do erro:' . $_FILES['file']['error'] . '");</script>';
        } else {
            if (move_uploaded_file($_FILES['theImage']['tmp_name'], 'tmp/' . $_FILES['theImage']['name'])) {
                if ($_POST[source] == 'aboutMe') {
                    $getOptions = '?tab=aboutMe';
                    $_SESSION['db_about']['photo'] = 'tmp/' . $_FILES['theImage']['name'];
                } else if ($_POST[source] == 'portfolio') {
                    if ($_POST['index'] == 'new') {
                        $teste = '';
                        $portfolioLength = count($_SESSION['db_portfolio']);
                        for($i = $portfolioLength; $i > 0; $i--){
                            $t = $i - 1;
                            $_SESSION['db_portfolio'][$i] = $_SESSION['db_portfolio'][$t];
                        }
                        $_SESSION['db_portfolio'][0] = 'tmp/' . $_FILES['theImage']['name'] . '§§§§§0';
                        $_POST['index'] = count($_SESSION['db_portfolio']) - 1;
                    } else {
                        $arrItem = explode('§', $_SESSION['db_portfolio'][$_POST['index']]);
                        $arrItem[0] = 'tmp/' . $_FILES['theImage']['name'];
                        $strItem = "";
                        foreach ($arrItem as $data) {
                            $strItem .= $data . '§';
                        }
                        $strItem = rtrim($strItem, '§');
                        $_SESSION['db_portfolio'][$_POST['index']] = $strItem;
                    }
                    $getOptions = '?tab=portfolio&portPage=' . $_POST['portPage'];
                }
                echo '<script>alert("Sucesso. A imagem foi movida para um local temporário, para salvá-la definitivamente, clique em \"Salvar Alterações\"."); window.location = "cms.php' . $getOptions . '";</script>';
            } else {
                echo '<script>alert("Ocorreu um problema ao tentar mover o arquivo para a pasta temporária.");</script>';
            }
        }
    }
}

function eraseTmp() {
    $dir = 'tmp/';
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != '.' && $file != '..') {
                    unlink($dir . $file);
                }
            }
        }
    } else {
        die("Erro ao abrir o diretório: $dir");
    }
}

if (!isset($_SESSION['login']) || !$_SESSION['login']) {
    if ($_GET[action] == 'login') {
        login();
    }
}

if ($_GET[action] == 'logout') {
    eraseTmp();
    session_destroy();
    Header('Location: ' . $_SERVER['PHP_SELF']);
} else if ($_GET[action] == 'save') {
    if (isset($_POST['postLength'])) {
        save();
    }
} else if ($_GET[action] == 'uploadImage') {
    uploadImage();
}
if (isset($_GET[dataSaved])) {
    echo '<script>alert("As alterações foram salvas com sucesso."); window.location = "cms.php";</script>';
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>CMS do site | Login</title>
        <script>
            var user = "<?php echo $_SESSION['user']; ?>";
            var tmp;
            var currentTab = "<?php echo (isset($_GET['tab']) ? $_GET['tab'] : 'homePage'); ?>";
            var current;
<?php if (isset($_GET['portIndex'])) echo 'var portItemChoice = ' . $_GET['portIndex'] . ';'; ?>
<?php if (isset($_GET['portPage'])) echo 'var chosenPortPage = "' . $_GET['portPage'] . '";'; ?>
    var database = new Object();
    var pageCounter = 1;
    var totalPages;
            
    function storeDatabase(){
        ////Homepage contents
        var strHome= "<?php
foreach ($_SESSION['db_home'] as $quote) {
    echo $quote . '|';
}
?>";
        strHome = strHome.substr(0, strHome.length - 1);
        var arrHome = strHome.split('|');
        database.homePage = new Array();
        for(i = 0; i < arrHome.length; i++){
            var arrQuote = arrHome[i].split('§');
            var obj = new Object();
            obj.author = arrQuote[0];
            obj.quote = arrQuote[1];
            
            database.homePage[i] = obj;
        }
        ////Homepage contents
        
        ////Portfolio contents
        var strPortfolio = "<?php
foreach ($_SESSION['db_portfolio'] as $item) {
    echo $item . '|';
}
?>";
        strPortfolio = strPortfolio.substr(0, strPortfolio.length - 1);
        var arrPortfolio = strPortfolio.split('|');
        database.portfolio = new Array();
        for(i = 0; i < arrPortfolio.length; i++){
            var arrItem = arrPortfolio[i].split('§');
            var obj = new Object();
            obj.thumb = arrItem[0];
            obj.name = arrItem[1];
            obj.desc = arrItem[2];
            obj.tech = arrItem[3].substr(13, (arrItem[3].length - 13));
            obj.link = arrItem[4];
            obj.status = arrItem[5];
            
            database.portfolio[i] = obj;
        }
        ////Portfolio contents
        
        ////AboutMe contents
        database.aboutMe = new Object();
        database.aboutMe.photo = "<?php echo $_SESSION['db_about']['photo']; ?>";
        database.aboutMe.desc = "<?php echo $_SESSION['db_about']['desc']; ?>";
        var strSkills = "<?php
foreach ($_SESSION['db_about']['skills'] as $skill) {
    echo $skill . '|';
}
?>";
        strSkills = strSkills.substr(0, strSkills.length - 1);
        var arrSkills = strSkills.split('|');
        database.aboutMe.skills = new Array();
        for(i = 0; i < arrSkills.length; i++){
            var arrSkill = arrSkills[i].split('§');
            var obj = new Object();
            obj.name = arrSkill[0];
            obj.level = arrSkill[1];
            
            database.aboutMe.skills.push(obj);
        }
        ////AboutMe contents
    }
        </script>   
        <script src="cmsFunctions.js"></script>
        <script>
            window.onload = function(){
                if(<?php
if (isset($_SESSION['login'])) {
    echo 1;
} else {
    echo 0;
}
?>){
        if(<?php echo $_SESSION['login']; ?>) start();
        else alert("Nome de usuário e/ou senha inválidos.");
<?php if (isset($_SESSION['login']) && $_SESSION['login'] == 0) session_destroy(); ?>
    }
}
        </script>
        <style>
            body{
                font-family:arial;
            }
            li{
                list-style-type: none;
                text-align:left;
            }
            .mainLink{
                text-decoration: none;
                font-size: 22px;
                color: #0000ff;
            }
            #homePage a{
                text-decoration:none;
                color:#000000;
            }

            #homePage a:hover{text-decoration:underline;}

            #portfolio a{
                text-decoration:none;
                color:#000000;
            }

            #portfolio a:hover{text-decoration:underline;}

            #lightBox{
                background-color:#000000;
                width:100%;
                height:100%;
                top: 0px;
                left: 0px;
                position:absolute;
                z-index: 1000;
                opacity: 0.6;
            }

            #lightBoxContent{
                background-color: #f0f0f0;
                width:500px;
                height:250px;
                position:absolute;
                top: 225px;
                left: 400px;
                z-index:1001;
                border:1px solid #000000;
            }

            #formLogIn input{
                width:150px;
            }
        </style>
    </head>
    <body>
    <center>
        <form id="formLogIn" action="?action=login" method="post">
            <table style="border:1px solid #777777;border-radius:7px;box-shadow:2px 2px 4px #555555;padding:0px 20px 0px 20px;">
                <tr style="color:#777777;"><td colspan="2" align="center"><h3>Login</h3></td></tr>
                <tr>
                    <td><label for="user">Usuário: </label></td>
                    <td><input id="user" type="text" name="user" value="<?php echo $_POST[user]; ?>"/></td>
                </tr>
                <tr>
                    <td><label for="password">Senha: </label></td>
                    <td><input id="password" type="password" name="password" value="<?php echo $_POST[password]; ?>"/></td>
                </tr>
                <tr>
                    <td>&nbsp;<td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" name="send" value="Entrar" style="width:100%;height:30px;margin-bottom:20px;"/></td>
                </tr>
            </table>
        </form>
    </center>
    <div id="lightBox" style="display:none;"></div>
    <div id="lightBoxContent" style="display:none;">
        <center>
            <table>
                <tr><td align ="center"><label for="theImage">Enviar imagem de thumbnail:</label></td></tr>
                <tr><td align ="center">
                        <form style="margin:auto;" action="?action=uploadImage" method="post" enctype="multipart/form-data">
                            <input type="file" name="theImage" onChange="uploadImage(event)"/>
                            <input type="hidden" name="source" value="portfolio"/>
                            <input type="hidden" name="index" value="new"/>
                            <input type="hidden" name="portPage" value="last"/>
                        </form>
                    </td>
                </tr>
                <tr><td align ="center"><input type="button" value="Fechar" onClick="overlayLightBox()"></td></tr>
            </table>
        </center></div>
    <div id="adminPanel" style="display:none;">
        <table width="100%">
            <tr>
                <td width ="25%" align="center"><a class="mainLink" onClick="mainLinkClickHandler(event)" name="homePage" href="#homePage">Home Page</a></td>
                <td width ="25%" align="center"><a class="mainLink" onClick="mainLinkClickHandler(event)" name="portfolio" href="#portfolio">Portfolio</a></td>
                <td width ="25%" align="center"><a class="mainLink" onClick="mainLinkClickHandler(event)" name="aboutMe" href="#aboutMe">Sobre</a></td>
                <td width ="25%" align="center" style="border-left:1px solid #000000;"><input type="button" width="33%" value="Salvar alterações" onClick="save()"></td>
            </tr>
        </table>
        <hr/>
        <div class="content" id="homePage">
            <table width="60%">
                <tr>
                    <td width="25%" align="center" valign="top">
                        <h4>Citações famosas:</h4>
                        <ul id="quotesList">
                            <?php
                            foreach ($_SESSION['db_home'] as $key => $value) {
                                echo '<li class="quoteLink"><a title="Remover" name="' . $key . '" href="#delQuote' . ($key + 1) . '" onClick="removeQuote(event)"><img style="margin:5px 0px 0px 0px;" src="img/delete.png"></a>&nbsp;<a name="' . $key . '" href="#famousQuote' . ($key + 1) . '" onClick="changeQuote(event)">Frase ' . ($key + 1) . '</a></li>';
                            }
                            ?>
                        </ul>
                    </td>
                    <td width="75%" align="center" valign="top">
                        <table>
                            <tr><td><label for="quoteAuthor">Autor: </label></td></tr>
                            <tr>
                                <td><input width="100%" type="text" id="quoteAuthor" name="0" value="" onChange="updateQuoteData(event)"/></td>
                            </tr>
                            <tr><td><label for="quote">Frase: </label></td></tr>
                            <tr>
                                <td><textArea style="width:100%;height:100px;resize:none;" id="quote" name="0" onChange="updateQuoteData(event)"></textArea></td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td align="center"><input type="button" width="33%" value="+ Nova Frase" onClick="newQuote()"></td>
                    <td align="center"></td>
                </tr>
            </table>
        </div>
        <div class="content" id="portfolio" style="display:none;">
            <table>
                <tr>
                    <td valign="top" style="width:20%;">
                        <table>
                            <tr>
                                <td id="showCounter"></td>
                            </tr>
                            <tr>
                                <td id="pageCounter"></td>
                            </tr>
                            <tr>
                                <td><div id="portfolioList"></div><center><input type="button" value="+ Novo &Iacute;tem" onClick="newPortfolio()"/></center></td>
                </tr>
            </table>
            </td>
            <td valign="top" style="width:20%;">
                <img id="portfolioThumb" src="" style="border:1px solid #000000;"/>
                <form action="?action=uploadImage" method="post" enctype="multipart/form-data">
                    <label for="theImage">Enviar imagem:</label>
                    <input type="file" name="theImage" onChange="uploadImage(event)"/>
                    <input type="hidden" name="source" value="portfolio"/>
                    <input type="hidden" id="thumbIndex" name="index" value=""/>
                    <input type="hidden" id="portPage" name="portPage" value=""/>
                </form>
            </td>
            <td valign="top" style="width:20%;">
                <table>
                    <tr>
                        <td><label for="portName">Nome: </label></td>
                        <td><input style="width:300px;" type="text" id="portName" name="portName" value="" onChange="updatePortfolioData(event)"/></td>
                    </tr>
                    <tr>
                        <td><label for="portDesc">Descri&ccedil;&atilde;o: </label></td>
                        <td><textarea style="resize:none;width:300px;height:100px;" type="text" id="portDesc" name="portDesc" onChange="updatePortfolioData(event)"></textarea></td>
                    </tr>
                    <tr>
                        <td><label for="portTech">Tecnologias: </label></td>
                        <td><input style="width:300px;" type="text" id="portTech" name="portTech" value="" onChange="updatePortfolioData(event)"/></td>
                    </tr>
                    <tr>
                        <td><label for="portURL">Endereço web: </label></td>
                        <td><input style="width:300px;" type="text" id="portURL" name="portURL" value="" onChange="updatePortfolioData(event)"/></td>
                    </tr>
                    <tr>
                        <td>
                            <label for="portStatus">Status: </label>
                        </td>
                        <td>
                            <select id="portStatus" name="portStatus" onChange="updatePortfolioData(event)">
                                <option name="statusOption" value="1">Ativo</option>
                                <option name="statusOption" value="0">Inativo</option>
                            </select>
                        </td>
                    </tr>
                </table>
            </td>
            </tr>
            </table>
        </div>
        <div class="content" id="aboutMe" style="display:none;">
            <table>
                <tr>
                    <td valign="top" align="center">
                        <img id="aboutMePhoto" src="" style="border:1px solid #000000;"/>
                        <form action="?action=uploadImage" method="post" enctype="multipart/form-data">
                            <label for="theImage">Trocar foto:</label>
                            <input type="file" name="theImage" onChange="uploadImage(event)"/>
                            <input type="hidden" name="source" value="aboutMe"/>
                        </form>
                    </td>
                    <td valign="top" align="center"><label for="aboutMeDesc">Sobre mim:</label><br/><textArea id="aboutMeDesc" name="aboutMeDesc" style="resize:none;width:400px;height:189px;" onChange="updateAboutMeData(event)"></textArea></td>
                    <td valign="top" style="width:400px;" align="center"><table><thead><tr><th></th><th>Nome:</th><th>Nv.:</th></tr></thead><tbody id="skillsTable"></tbody></table><input type="button" onClick="newSkill()" value="+ Nova Skill"/></td>
                </tr>
            </table>
        </div>
    </div>
</body>
</html>